package com.atguigu.juc.day02;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        //  6辆汽车 抢占3个停车位！
        Semaphore semaphore = new Semaphore(3);

        //  抢占
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    //  获取资源
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"获取了停车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(6));
                    System.out.println(Thread.currentThread().getName()+"离开停车位");
                    //  释放资源
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

    }
}
